package com.superitem.school.controller;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import com.superitem.school.pojo.User;
import com.superitem.school.service.UserService;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    UserService userService;

    @RequestMapping("/toupdate/{id}")
    public String toUpdate(@PathVariable("id") long id,Model model){
        User user = userService.queryById(id);
        System.out.println(user);
        model.addAttribute("user", user);
        return "user/update";

    }

    @RequestMapping("/update")
    public String update(User user, Model model){
        userService.userUpdate(user);
        model.addAttribute("user", userService.queryById(Long.valueOf(user.getUid())));
        return "user/show";
    }

    @RequestMapping("/tosave")
    public String toSave(){
        return "user/save";
    }


    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
    @RequestMapping("/insert")
    public String insert(User user, Model model){
        userService.userSave(user);
        User user1 = userService.queryById(Long.valueOf(user.getUid()));
        model.addAttribute("user", user1);
        return "user/show";
    }

    @Value("${page.size}")
    String pageSize;
    @RequestMapping("/showtable/{pageNum}")
    public String showTable(@PathVariable("pageNum")Integer pageNum, Model model){
        PageInfo<User> pageinfo = userService.selectAllUser(pageNum,Integer.valueOf(pageSize));
        model.addAttribute("pageInfo", pageinfo);
        return "user/showtable";
    }

    @RequestMapping("/deleteById/{id}")
    public String removeUser(@PathVariable("id") Integer id){
        userService.deleteUserById(id);
        return "user/deleteSuccess";
    }


    @InitBinder
    public void initBinder(ServletRequestDataBinder binder){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        binder.registerCustomEditor(Date.class, new CustomDateEditor(sdf, true));
    }
}
